import { purchaseCourse } from '../../api/user';
import { wxPay } from '../../api/pay';
import { timeoutTask } from '../../utils/index';

const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        origin: '',
        albumId: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.origin) {
            this.setData({
                origin: options.origin,
            });
        }
        if (options.albumId) {
            this.setData({
                albumId: options.albumId,
            });
        }
        if (this.data.origin === 'purchaseCourse') {
            this.purchaseCourse();
        }
    },
    // 购买课程
    purchaseCourse: function () {
        purchaseCourse({
            albumId: this.data.albumId,
        }).then((res) => {
             
            return wxPay(res);
        }).then(() => {
            wx.showToast({ title: '支付成功', icon: 'none' })
            app.globalData.isH5NeedRefresh = true;
            timeoutTask(() => {
                wx.navigateBack();
            }, 500);
        }).catch((err) => {
              
            if (err.errMsg === 'requestPayment:fail cancel') {
                wx.navigateBack();
            } else {
                wx.showToast({ title: '支付失败,请重新授权登录!', icon: 'none' });
                wx.clearStorageSync();
                timeoutTask(() => {
                    wx.switchTab({ url: '/pages/index/index' });
                }, 1000);
            }

        });
    },
})